<?php
/**
 * 产品图库: 施工案例, 设计师作品等
 */
namespace app\admin\controller;

use think\Request;
use app\admin\model\Pictures as ImgModel;

class Pictures extends Base
{
    protected $img_model;

    public function __construct(Request $request = null)
    {
        parent::__construct($request);

        $this->img_model = new ImgModel();
    }

    public function index($cid = null)
    {
        return $this->fetch();
    }

    public function add()
    {
        return $this->fetch();
    }


    public function show($cid, $sid = null)
    {
        $map['status'] = 1;
        $map['cid'] = $cid;
        $map['sid'] = $sid;
    
        $data = $this->img_model->where($map)->select();
        // var_dump($map);
        // return json_encode($data);
        $this->assign('data', $data);
        $this->assign('map', $map);
        return $this->fetch();
    }

    public function showAdd($cid, $sid)
    {
        if (Request::instance()->isPOST()) {
            $file = request()->file('img');
            
            if ($file) {
                $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads');
                if ($info) {
                    $filename = $info->getSaveName();
                    $thumb = make_thumb($filename);
                    $thumb = ($thumb != false) ? DS . 'uploads' . DS . $thumb : '';
                } else {
                    // 上传失败获取错误信息
                    $this->error($file->getError());
                }
            } else {
                $thumb = '';
            }

            try {
                $this->img_model->save([
                    'cid' => $cid,
                    'sid' => $sid,
                    'thumb' => $thumb,
                    'image' => DS.'uploads'.DS.$filename,
                    'sort' => intval(input('post.sort')),
                    'mtime' => time()
                ]);
            } catch (\Exception $e) {
                $msg = $e->getMessage();

                $this->error("错误代码:" . $msg);
            }
            $this->success('添加成功', 'show?cid='.$cid.'&sid='.$sid);
        }
        $this->assign('map', ['cid'=>$cid, 'sid'=>$sid]);
        return $this->fetch();
    }

    /**
     * 标记删除, 只在数据库里做了标记没从磁盘上删除, 可恢复
     */
    public function del($id = null)
    {
        if (Request::instance()->isAjax()) {
            $list = [];
            if (is_array($id)) {
                foreach ($id as $val) {
                    $list[] = ['id'=>$val, 'status'=>0];
                }
            } else {
                $list[] = ['id'=>$id, 'status'=>0];
            }

            if ($this->img_model->saveAll($list)) {
                return ['code'=>2,'msg'=>config('msg.1003')];
            } else {
                $this->error(config('msg.1004'));
            }
        }
    }

    /**
     * 回收站
     */
    public function recycle()
    {
    }

    /**
     * 磁盘删除不可恢复
     */
    public function realDel($id = null)
    {
        return 'test';
    }
}
